//
//  Download.m
//  SmileRead
//
//  Created by dllo on 15/8/27.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "Download.h"
#import "AFNetworking.h"
#import "Path.h"

@interface Download ()

@end

@implementation Download

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

// 类方法, 下载成功或已经下载就返回yes, 否则返回no.
+ (instancetype) downloadWithSaveFileName:(NSString *)saveFile URLString:(NSString *)urlString
{
    Download *load = [[Download alloc] init];
    
    // 先判判断现在文件是否存在
    NSString *string = [Path pathOfLibraryWithFileName:saveFile];
    
    // 存放歌曲路径的文件的路径
    NSString *path = [NSString stringWithFormat:@"%@/%@", string, saveFile];
    
#warning 歌曲的路径名为自己的url
    // 存放歌曲的路径
    NSString *pathOfSong = [NSString stringWithFormat:@"%@/%@", string, urlString];
    
     NSFileManager *file = [NSFileManager defaultManager];
    
    // 若果文件存在, 见文件中的数据转换为数组, 然后遍历数组
    if ([file fileExistsAtPath:path]) {
        
        // 取出数据
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        // 将数据转化为数组
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 便利数组
        NSInteger count = 0;
        for (int i = 0; i < array.count; i++) {
            if ([pathOfSong isEqualToString:array[i]]) {
                NSLog(@"歌曲已经下载");
                count++;
            }
        }
        if (count > 0) {
            // 说明已经下载
            return [load autorelease];
        }
        else {
            [load startDownLoadWithURLString:urlString pathOfSong:pathOfSong];
        }
    }
    // 文件不存在
    else {
        
        // 先创建一个数组放入文件中,
        NSMutableArray *array = [NSMutableArray array];
        [array writeToFile:path atomically:YES];
        [load startDownLoadWithURLString:urlString pathOfSong:pathOfSong];
    }
    return [load autorelease];
}


- (void)startDownLoadWithURLString:(NSString *)urlStr pathOfSong:(NSString *)pathOfSong
{
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *opreation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    //opreation.inputStream = [NSInputStream inputStreamWithURL:url];
    
    [opreation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 下载成功
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
       //下载失败
        
    }];

}



- (void)finshDownLoad
{
    NSLog(@"下载成功");
}

- (void)failDownLoad
{
    NSLog(@"下载失败");
}




- (void)dealloc
{
    Block_release(_myBlock);
    [super dealloc];
}


@end
